package org.dbstar.scheduler.serializer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

/**
 * 将需要持久化的对象转换成property格式
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-9
 */
public class PropertySerializer<T extends PropertySerializable> implements Serializer<T> {
	@Override
	public void serialize(T object, OutputStream outputStream, boolean close) throws IOException {
		Properties properties = new Properties();
		try {
			String className = object.getClass().getName();
			properties.setProperty(PropertySerializable.class.getName(), className);
			try {
				object.serialize(new PropertySerializeHelper(properties, className));
			} catch (Throwable e) {
				throw new IOException("Failed to serialize object type", e);
			}
			properties.store(outputStream, object.toString());
		} finally {
			if (close) {
				IOUtils.closeQuietly(outputStream);
			}
		}
	}

	@Override
	public T deserialize(InputStream inputStream, boolean close) throws IOException {
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
			try {
				String className = properties.getProperty(PropertySerializable.class.getName());
				@SuppressWarnings("unchecked")
				T object = (T) Class.forName(className).newInstance();
				object.deserialize(new PropertySerializeHelper(properties, object.getClass().getName()));
				return object;
			} catch (Throwable e) {
				throw new IOException("Failed to deserialize object type", e);
			}
		} finally {
			if (close) {
				IOUtils.closeQuietly(inputStream);
			}
		}
	}
}
